import cgi
import uuid
import datetime
from google.appengine.ext import db

class User(db.Model):
  username = db.StringProperty()
  screenname = db.StringProperty()
  password = db.StringProperty()
  groups = db.StringProperty()
  ticket = db.StringProperty()
  timestamp = db.DateTimeProperty()


def GALogin(username,password):
  users = db.GqlQuery("SELECT * FROM User WHERE username = '" + username + "' and password = '" + password +"'");
  for u in users:
    u.ticket = str (uuid.uuid1())
    u.timestamp = datetime.datetime.now()
    u.put()
    return u
  return User()

def GAValidateTicket(ticket):
  users = db.GqlQuery("SELECT * FROM User WHERE ticket = '" + ticket + "'");
  for u in users:
    delta = abs (datetime.datetime.now() - u.timestamp)
    print "got a delta of " + str(delta) + " compare to " + str(datetime.timedelta(0,60*60*12))+  " <br>"
    if (delta < datetime.timedelta(0,60*60*12)):
      print "in if .... "
      # refresh timestamp 
      u.timestamp = datetime.datetime.now()
      u.put()
      return u
    else:
      print "in else .... "
      u.ticket = None
      return u
  # timestamp expired or didn't exist
  return User()


  
#user = User()
#user.username = "al"
#user.screenname = "Al"
#user.password = "password"
#user.groups = "admin,user"
#user.put()

